package com.zn.opit.tech.easyexcel.utils;

import com.zn.opit.tech.easyexcel.domain.excel.exp.ImportExpVO;
import com.zn.opit.tech.easyexcel.exception.EasyExcelException;
import com.zn.opit.tech.easyexcel.exception.EasyExcelExtExceptionTypes;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class ValidationUtil {

    public static Validator getValidator() {
        return validator;
    }

    static Validator validator;

    static {
        ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
        validator = validatorFactory.getValidator();
    }

    public static <T> void doValidate(List<T> var1, Class<?>... var2) {
        List<ImportExpVO> expVOList = new ArrayList<>();
        int rowNum = 1;
        for (T var0 : var1) {
            rowNum++; // 跳过标题行, 此为excel的行号
            List<String> errMsg = new ArrayList<>();
            Set<ConstraintViolation<T>> validateRstSet = ValidationUtil.getValidator().validate(var0, var2);
            for (ConstraintViolation<T> constraintViolation : validateRstSet) {
                errMsg.add(constraintViolation.getMessage());
            }
            if (errMsg.size() > 0) {
                expVOList.add(ImportExpVO.builder().rowNum(rowNum).errMsg(errMsg).build());
            }
        }
        if (expVOList.size() > 0) {
            // 组装异常数据
            throw new EasyExcelException(EasyExcelExtExceptionTypes.DATA_VALID_FAILED, expVOList);
        }
    }
}
